import React from 'react';
import { Button, Menu, message } from 'antd';
const Item = Menu.Item;
import {
    WeaErrorPage,
    WeaTools,
    WeaDialog,
    WeaLeftRightLayout,
    WeaRightMenu,
    WeaMoreButton,
    WeaLocaleProvider
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import HpBaseElement from './HpBaseElement';
import Homepage from './Homepage';
import PortalMenu from './PortalMenu';
import { handlePortalSynize, onShowOrHideAllE, openFavouriteBrowser, showHelp } from '../util/rcmenu';
//门户组件
class PortalSetting extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            params: {},
            visible: false,
            loading: false,
            title:getLabel(19650,'设置元素'),
            data: {
                portalinfo: {},
                hpbaseelements:[],
                hpsettingmenu:[],
                rcmenu:[],
            },
            showLeft: true,
            portalmenu: {},
            showDrop: false,
            isShrink: false,
        }
        this.onChangeLabel = this.onChangeLabel.bind(this);
        this.onShowDrop = this.onShowDrop.bind(this);
        this.getButtons = this.getButtons.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.handleOnSetting = this.handleOnSetting.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.handleRefreshPortal = this.handleRefreshPortal.bind(this);
        this.handleAddElementToPortalStart = this.handleAddElementToPortalStart.bind(this);
        this.handleAddElementToPortal = this.handleAddElementToPortal.bind(this);
    }
    onShowDrop(){
        this.setState({
            showDrop: !this.state.showDrop,
        });
    }
    getButtons(){
        let isRedirectUrl = '0';
        if(this.state.data.portalinfo){
            isRedirectUrl = this.state.data.portalinfo.isRedirectUrl;
        }
        let btns = [];
        if(isRedirectUrl != '1'){
            const { hpsettingmenu } = this.state.data;
            if (hpsettingmenu && hpsettingmenu.length) {
                hpsettingmenu.map((menu, i)=>{
                    if(menu.key == 'more'){
                        btns.push(<OperateMenu ecId={`${this && this.props && this.props.ecId || ''}_OperateMenu@2aqt5n@${menu.key}`} dropMenuDatas={this.getRightMenu()} onShowDrop={this.onShowDrop} onDropMenuClick={this.onRightMenuClick} showDrop={this.state.showDrop}><Button ecId={`${this && this.props && this.props.ecId || ''}_Button@33k54x@${menu.key}`} onClick={this.onShowDrop}>{menu.label}</Button></OperateMenu>);
                    }else{
                        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t520pc@${menu.key}`} type={i === 4 ? '' : 'primary'} onClick={this.onRightMenuClick.bind(this,menu.key)}>{menu.label}</Button>);
                    }
                });
            } else {
                btns.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@44wyqz`} datas={[]}/>);
            }
        }
        return btns;
    }
    getRightMenu(){
        let btns = [];
        let isRedirectUrl = '0';
        if(this.state.data.portalinfo){
            isRedirectUrl = this.state.data.portalinfo.isRedirectUrl;
        }
        if(isRedirectUrl != '1'){
            const { rcmenu } = this.state.data;
            if(rcmenu){
                rcmenu.map(menu=>{
                    btns.push({
                        key: menu.key,
                        icon: <i className={menu.icon}/>,
                        content: menu.label,
                    }); 
                });
            }
        }
        return btns
    }
    onChangeLabel(list, key, bool, label1, lable2){
        for (let i =0; i < list.length; i++) {
            let item = list[i] || {};
            if(item.key == key){
                if(bool){
                    item.label = label1;
                    if(item.label=="全部收缩"||item.label=="Shrink All "){
                        item.icon = "icon-coms-All-contraction"
                    }
                    if(item.label=="显示元素库"||item.label=="顯示元素庫"||item.label=="Show Element Lib "||item.label=="Display element library "||item.label=="显示元素庫"){
                        item.icon = "icon-coms-display"
                    }
                    if(item.label=="全部展开"||item.label=="outspread all "||item.label=="全部展開"){
                        item.icon = "icon-coms-All-unfolding"
                    }
                    if(item.label=="隐藏元素库"||item.label=="Hidden element library "||item.label=="隱藏元素庫"){
                        item.icon = "icon-coms-hide"
                    }
                }else{
                    item.label = lable2;
                    if(item.label=="全部收缩"||item.label=="Shrink All "){
                        item.icon = "icon-coms-All-contraction"
                    }
                    if(item.label=="显示元素库"||item.label=="顯示元素庫"||item.label=="Show Element Lib "||item.label=="Display element library "||item.label=="显示元素庫"){
                        item.icon = "icon-coms-display"
                    }
                    if(item.label=="全部展开"||item.label=="outspread all "||item.label=="全部展開"){
                        item.icon = "icon-coms-All-unfolding"
                    }
                    if(item.label=="隐藏元素库"||item.label=="Hidden element library "||item.label=="隱藏元素庫"){
                        item.icon = "icon-coms-hide"
                    }
                }
                break;
            }
        }
    }
    onRightMenuClick(key){
        const { params, showLeft, isShrink, data } = this.state;
        const { hpid, subCompanyId, isSetting } = params;
        switch(key){
            case 'updatesynihp':
            case 'completesynihp':
                handlePortalSynize({
                    hpid: hpid,
                    subCompanyId: subCompanyId,
                    method: key
                });
                break;
            case 'shrinkAll':
                this.setState({
                    isShrink: !isShrink
                });
                this.onChangeLabel(data.rcmenu,'shrinkAll', this.state.isShrink, getLabel(18466,'全部收缩'), getLabel(16216,'全部展开'));
                this.onChangeLabel(data.hpsettingmenu,'shrinkAll', this.state.isShrink, getLabel(18466,'全部收缩'), getLabel(16216,'全部展开'));
                onShowOrHideAllE(isSetting, !isShrink);
                break;
            case 'store':
                openFavouriteBrowser();
                break;
            case 'help':
                showHelp();
                break;
            case 'hiddenElementLib':
                this.setState({
                    showLeft: !showLeft
                });
                this.onChangeLabel(data.rcmenu,'hiddenElementLib', this.state.showLeft, getLabel(19613,"显示元素库"),getLabel(19614,"隐藏元素库"));
                this.onChangeLabel(data.hpsettingmenu,'hiddenElementLib', this.state.showLeft, getLabel(19613,"显示元素库"), getLabel(19614,"隐藏元素库"));
                break;
        }
    }
    handleOnSetting(params){
        this.setState({visible: true, loading: true});

        let title = params.title || ''
        if(params.viewtype === 'priview'){
            WeaTools.callApi('/api/portal/hpsetting/hpsettinginfo', 'POST', params).then((result) => {
                if(result.status == '2'){
                    message.error(result.errormsg);
                    return;
                }
                if(params.module === 'mainpage'){
                    WeaTools.callApi('/api/portal/hpsetting/portalmenu', 'POST', {hpid: params.hpid}).then((data) => {
                        if(data.status == '2'){
                            message.error(data.errormsg);
                            return;
                        }
                        window.isPortalRender = true;
                        this.setState({
                            params,
                            loading: false,
                            portalmenu: data,
                            data: {
                                hpbaseelements:[],
                                hpsettingmenu:[],
                                rcmenu:[],
                                portalinfo:result.portalinfo
                            },
                            title: title ? title + ' - '+getLabel(221, '预览') : getLabel(221, '预览'),
                        });
                    });
                }else{
                    this.setState({
                        params,
                        loading: false,
                        data: {
                            hpbaseelements:[],
                            hpsettingmenu:[],
                            rcmenu:[],
                            portalinfo:result.portalinfo
                        },
                        portalmenu: {},
                        title: title ? title + ' - '+getLabel(221, '预览') : getLabel(221, '预览'),
                    });
                }
            });
        }else{
            WeaTools.callApi('/api/portal/hpsetting/hpsettinginfo', 'POST', params).then((data) => {
                if(data.status == '2'){
                    message.error(data.errormsg);
                    return;
                }
                window.isPortalRender = true;
                this.setState({
                    params,
                    loading: false,
                    data,
                    portalmenu: {},
                    title: title ? title + ' - '+ getLabel(19650, '设置元素') : getLabel(19650, '设置元素'),
                });
            });
        }
    }
    handleCancel(){
        this.setState({
            visible: false,
        });
    }
    handleRefreshPortal(params){
        if(this.refs.homepage) this.refs.homepage.handleRefresh(params);
    }
    handleAddElementToPortalStart() {
        this.setState({loading: true});
    }
    handleAddElementToPortal(element, areaflag, index){
        this.setState({loading: false});
        window.isPortalRender = true;
        this.refs.homepage.handleAddElement(element, areaflag, index);
    }
    componentDidMount(){
        window.handlePortalSetting = this.handleOnSetting.bind(this);
    }
    render() {
        const { params, title, visible, loading, data, portalmenu, showLeft } = this.state;
        const { hpid, subCompanyId, isSetting, viewtype, module } = params;
        const { portalinfo } = data;
        let html = <div/>;
        if(hpid){
            if(portalinfo.isRedirectUrl == '1'){
                html = <iframe frameBorder="no" 
                            className="custompageIframe" 
                            src={portalinfo.redirectUrl} 
                            style={{borderCollapse:'collapse',width:'100%',height:'100%'}}/>
            }else{
                html = <div id="e9PortalSetting" className="portal-e9setting">
                                    <Homepage ecId={`${this && this.props && this.props.ecId || ''}_Homepage@ui99he`} {...params} ref="homepage"/>
                                  </div>
                if(viewtype !== 'priview'){
                    html = visible && <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@f2zcuf`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                      <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@y26h2d`} 
                            isNew={true} 
                            showLeft={showLeft} 
                            leftWidth={150} 
                            leftCom={<HpBaseElement ecId={`${this && this.props && this.props.ecId || ''}_HpBaseElement@138qv3`} handleRefreshPortal={this.handleRefreshPortal} handleAddStart={this.handleAddElementToPortalStart} handleAdd={this.handleAddElementToPortal} params={params} list={data.hpbaseelements}/>}
                            onCollapse={bool => {
                                this.setState({showLeft: bool});
                                this.onChangeLabel(data.rcmenu,'hiddenElementLib', bool, getLabel(19614,"隐藏元素库"), getLabel('19613',"显示元素库"));
                                this.onChangeLabel(data.hpsettingmenu,'hiddenElementLib', bool, getLabel(19614,"隐藏元素库"), getLabel('19613',"显示元素库"));
                            }}
                        >
                        {html}
                      </WeaLeftRightLayout>
                   </WeaRightMenu>;
            }  
            }
        }

        return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zzwwa2`} title={title}
                  visible={visible}
                  scalable
                  loading={loading}
                  closable={true}
                  onCancel={this.handleCancel}
                  icon='icon-coms-portal'
                  iconBgcolor='#1a57a0'
                  maskClosable={false}
                  buttons={this.getButtons()}
                  style={{width:document.body.clientWidth - 100,height:document.body.clientHeight - 180}}
                  zIndex={800}>
                  {module === 'mainpage' ? <PortalMenu ecId={`${this && this.props && this.props.ecId || ''}_PortalMenu@7dnyod`} hpid={hpid} subCompanyId={subCompanyId} portalmenu={portalmenu} handleRefresh={this.handleRefreshPortal}/> : ''}
                  {html}
            </WeaDialog>
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@az6etz`} msg={ hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
PortalSetting = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(PortalSetting);
export default PortalSetting;


class OperateMenu extends React.Component{
    render(){
        const { dropMenuDatas, onDropMenuClick, onShowDrop, showDrop, children } = this.props;
        const menu = dropMenuDatas
            ? <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@o8rl89`} mode='vertical' onClick={o => {
              if (typeof onDropMenuClick === 'function') onDropMenuClick(o.key);
              dropMenuDatas.forEach(d => {
                if (d.key === o.key && typeof d.onClick === 'function') d.onClick(o.key);
              });
            }}
            >
              {
                dropMenuDatas.map((d, i) => {
                  return (
                    <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@jconpd@${d.key || i}`} key={d.key || i} disabled={d.disabled}>
                      <span className='wea-right-menu-icon'>{d.icon}</span>
                      {d.content}
                     </Item>
                  );
                })
              }
            </Menu>
            : '';
        return <div className='portal-portalsetting-moremenu-pop'>
                <div className='wea-new-top-drop-menu wea-right-menu' style={{display: showDrop ? 'block' : 'none'}} onMouseLeave={onShowDrop}>
                    <div className='wea-right-menu-icon-background'></div>
                    {menu}
                </div>
                {children}
                </div>

    }
}




